package user

import (
	"gitee.com/flwwsg/apiserver/handler"
	"gitee.com/flwwsg/apiserver/model"
	"gitee.com/flwwsg/apiserver/pkg/errno"
	"github.com/gin-gonic/gin"
)

func Create(c *gin.Context) {
	var r CreateRequest
	if err := c.Bind(&r); err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}
	u := model.UserModel{
		Username: r.Username,
		Password: r.Password,
	}
	//validate data
	if err := u.Validate(); err != nil {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}
	exist, err := model.GetUser(u.Username)
	if err != nil {
		handler.SendResponse(c, errno.ErrUserExist, nil)
		return
	}
	//用户存在
	if exist.Username != "" {
		handler.SendResponse(c, errno.ErrUserExist, nil)
		return
	}
	//encrypt password
	if err := u.Encrypt(); err != nil {
		handler.SendResponse(c, errno.ErrEncrypt, nil)
		return
	}
	//create user
	if err := u.Create(); err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	resp := CreateResponse{Username: r.Username}
	handler.SendResponse(c, nil, resp)
}
